package com.enzo.security.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dc.base.mapper.account.AccountUserMapper;
import com.dc.base.po.account.AccountUser;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.User;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: oyc
 * @Date: 2019/1/29 14:19
 * @Description: 用户服务类
 */
@Service
public class SecurityUserService<T extends AccountUser> implements UserDetailsService {

    @Resource
    private AccountUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            QueryWrapper<AccountUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_account", username);
            AccountUser user = userMapper.selectOne(queryWrapper);
            if (user == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }
            //用户权限
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//            if (StringUtils.isNotBlank(user.getRoles())) {
//                String[] roles = user.getRoles().split(",");
//                for (String role : roles) {
//                    if (StringUtils.isNotBlank(role)) {
//                        authorities.add(new SimpleGrantedAuthority(role.trim()));
//                    }
//                }
//            }
            return new User(user.getUserName(), user.getUserPassword(), authorities);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
